using Microsoft.AspNetCore.Mvc;
using FServer.Core.Interfaces;

namespace FServer.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ServerController : ControllerBase
{
    private readonly IGameServerService _serverService;
    private readonly ILogger<ServerController> _logger;

    public ServerController(IGameServerService serverService, ILogger<ServerController> logger)
    {
        _serverService = serverService;
        _logger = logger;
    }

    /// <summary>
    /// 获取服务器列表
    /// </summary>
    /// <param name="region">区域筛选</param>
    /// <param name="serverType">服务器类型筛选</param>
    /// <returns>服务器列表</returns>
    [HttpGet("list")]
    public async Task<IActionResult> GetServerList([FromQuery] string? region = null, [FromQuery] string? serverType = null)
    {
        try
        {
            _logger.LogInformation("获取服务器列表: 区域={Region}, 类型={ServerType}", region, serverType);

            var servers = await _serverService.GetServerListAsync(region, serverType);

            var response = servers.Select(s => new
            {
                s.Id,
                s.Name,
                s.ServerId,
                s.ServerType,
                s.Status,
                s.IpAddress,
                s.TcpPort,
                s.KcpPort,
                s.HttpPort,
                s.WebSocketPort,
                s.MaxConnections,
                s.CurrentConnections,
                s.LoadPercentage,
                s.BusyLevel,
                s.Region,
                s.Description,
                s.IsRecommended,
                s.IsEnabled,
                s.LastHeartbeat
            });

            return Ok(new { Success = true, Servers = response });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取服务器列表失败");
            return StatusCode(500, new { Success = false, Message = "获取服务器列表失败" });
        }
    }

    /// <summary>
    /// 获取推荐服务器
    /// </summary>
    /// <param name="region">区域</param>
    /// <returns>推荐服务器</returns>
    [HttpGet("recommended")]
    public async Task<IActionResult> GetRecommendedServer([FromQuery] string? region = null)
    {
        try
        {
            _logger.LogInformation("获取推荐服务器: 区域={Region}", region);

            var server = await _serverService.GetRecommendedServerAsync(region);
            if (server == null)
            {
                return NotFound(new { Success = false, Message = "未找到推荐服务器" });
            }

            var response = new
            {
                Success = true,
                Server = new
                {
                    server.Id,
                    server.Name,
                    server.ServerId,
                    server.ServerType,
                    server.Status,
                    server.IpAddress,
                    server.TcpPort,
                    server.KcpPort,
                    server.HttpPort,
                    server.WebSocketPort,
                    server.MaxConnections,
                    server.CurrentConnections,
                    server.LoadPercentage,
                    server.BusyLevel,
                    server.Region,
                    server.Description,
                    server.IsRecommended,
                    server.IsEnabled,
                    server.LastHeartbeat
                }
            };

            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取推荐服务器失败");
            return StatusCode(500, new { Success = false, Message = "获取推荐服务器失败" });
        }
    }

    /// <summary>
    /// 获取服务器详细信息
    /// </summary>
    /// <param name="serverId">服务器ID</param>
    /// <returns>服务器信息</returns>
    [HttpGet("{serverId}")]
    public async Task<IActionResult> GetServer(Guid serverId)
    {
        try
        {
            _logger.LogInformation("获取服务器信息: {ServerId}", serverId);

            var server = await _serverService.GetServerAsync(serverId);
            if (server == null)
            {
                return NotFound(new { Success = false, Message = "服务器不存在" });
            }

            var response = new
            {
                Success = true,
                Server = new
                {
                    server.Id,
                    server.Name,
                    server.ServerId,
                    server.ServerType,
                    server.Status,
                    server.IpAddress,
                    server.TcpPort,
                    server.KcpPort,
                    server.HttpPort,
                    server.WebSocketPort,
                    server.MaxConnections,
                    server.CurrentConnections,
                    server.LoadPercentage,
                    server.BusyLevel,
                    server.Region,
                    server.Description,
                    server.IsRecommended,
                    server.IsEnabled,
                    server.LastHeartbeat,
                    server.CreatedAt,
                    server.UpdatedAt
                }
            };

            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取服务器信息失败: {ServerId}", serverId);
            return StatusCode(500, new { Success = false, Message = "获取服务器信息失败" });
        }
    }

    /// <summary>
    /// 更新服务器状态 (内部API)
    /// </summary>
    /// <param name="serverId">服务器ID</param>
    /// <param name="request">状态更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut("{serverId}/status")]
    public async Task<IActionResult> UpdateServerStatus(Guid serverId, [FromBody] ServerStatusUpdateRequest request)
    {
        try
        {
            _logger.LogInformation("更新服务器状态: {ServerId}, 状态={Status}, 连接数={Connections}, 负载={Load}%", 
                serverId, request.Status, request.CurrentConnections, request.LoadPercentage);

            var success = await _serverService.UpdateServerStatusAsync(
                serverId, 
                request.Status, 
                request.CurrentConnections, 
                request.LoadPercentage);

            if (!success)
            {
                return NotFound(new { Success = false, Message = "服务器不存在或更新失败" });
            }

            return Ok(new { Success = true, Message = "服务器状态更新成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新服务器状态失败: {ServerId}", serverId);
            return StatusCode(500, new { Success = false, Message = "更新服务器状态失败" });
        }
    }

    /// <summary>
    /// 服务器心跳 (内部API)
    /// </summary>
    /// <param name="serverId">服务器ID</param>
    /// <returns>心跳结果</returns>
    [HttpPost("{serverId}/heartbeat")]
    public async Task<IActionResult> Heartbeat(Guid serverId)
    {
        try
        {
            _logger.LogDebug("服务器心跳: {ServerId}", serverId);

            var success = await _serverService.HeartbeatAsync(serverId);
            if (!success)
            {
                return NotFound(new { Success = false, Message = "服务器不存在" });
            }

            return Ok(new { Success = true, Message = "心跳成功", Timestamp = DateTime.UtcNow });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "服务器心跳失败: {ServerId}", serverId);
            return StatusCode(500, new { Success = false, Message = "心跳失败" });
        }
    }
}

/// <summary>
/// 服务器状态更新请求
/// </summary>
public class ServerStatusUpdateRequest
{
    /// <summary>
    /// 服务器状态
    /// </summary>
    public string Status { get; set; } = "Online";
    
    /// <summary>
    /// 当前连接数
    /// </summary>
    public int CurrentConnections { get; set; }
    
    /// <summary>
    /// 负载百分比
    /// </summary>
    public int LoadPercentage { get; set; }
}
